﻿CREATE PROCEDURE [dbo].[yaf_forum_listread](
                @BoardID    INT,
                @UserID     INT,
                @CategoryID INT  = NULL,
                @ParentID   INT  = NULL)
AS
    BEGIN
        SELECT   a.CategoryID,
                 Category = a.Name,
                 ForumID = b.ForumID,
                 Forum = b.Name,
                 Description,
                 Topics = dbo.yaf_forum_topics(b.ForumID),
                 Posts = dbo.yaf_forum_posts(b.ForumID),
                 LastPosted = b.LastPosted,
                 LastMessageID = b.LastMessageID,
                 LastUserID = b.LastUserID,
                 LastUser = Isnull(b.LastUserName,(SELECT Name
                                                   FROM   yaf_User x
                                                   WHERE  x.UserID = b.LastUserID)),
                 LastTopicID = b.LastTopicID,
                 LastTopicName = (SELECT x.Topic
                                  FROM   yaf_Topic x
                                  WHERE  x.TopicID = b.LastTopicID),
                 b.Flags,
                 Viewing = (SELECT COUNT(1)
                            FROM   yaf_Active x
                            WHERE  x.ForumID = b.ForumID),
                 b.RemoteURL,
                 x.ReadAccess
        FROM     yaf_Category a
                 JOIN yaf_Forum b
                   ON b.CategoryID = a.CategoryID
                 JOIN yaf_vaccess x
                   ON x.ForumID = b.ForumID
        WHERE    a.BoardID = @BoardID
        AND ((b.Flags & 2) = 0
              OR x.ReadAccess <> 0)
        AND (@CategoryID IS NULL 
              OR a.CategoryID = @CategoryID)
        AND ((@ParentID IS NULL 
              AND b.ParentID IS NULL)
              OR b.ParentID = @ParentID)
        AND x.UserID = @UserID
        ORDER BY a.SortOrder,
                 b.SortOrder
    END


